//
//  PictureSelectorViewController.m
//  PikerView
//
//  Created by 张帅 on 15/10/7.
//  Copyright © 2015年 ZhangShuai. All rights reserved.
//

#define HMMaxPictureCount  9

#define HMPictureMargin 10
#define HMPictureCellWidth 80
#import "UIImage+extension.h"

#import "PictureSelectorViewController.h"
#import "UIButton+bottom.h"

@interface PictureSelectorViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,PictureSelectorCellDelegate>

@property(nonatomic,assign) NSInteger currentIndex;


@end

@implementation PictureSelectorViewController

static NSString *PictureSelectorCellID=@"PictureSelectorCellID";

-(NSMutableArray *)pictures{
    if (_pictures==nil) {
        _pictures=[NSMutableArray array];
    }
    return _pictures;

}

-(instancetype)init{

     UICollectionViewFlowLayout *layout =[[UICollectionViewFlowLayout alloc] init];
    
    if (self==[super init]) {
     
        layout.itemSize =CGSizeMake(HMPictureCellWidth, HMPictureCellWidth);
        layout.minimumInteritemSpacing = HMPictureMargin;
        
        layout.minimumLineSpacing=HMPictureMargin;
        
        layout.sectionInset = UIEdgeInsetsMake(HMPictureMargin, HMPictureMargin, HMPictureMargin, HMPictureMargin);
        
        
    }
    return [self initWithCollectionViewLayout:layout];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.collectionView.backgroundColor =[UIColor colorWithWhite:0.95 alpha:1];
    
    [self.collectionView registerClass:[PictureSelectorCell class] forCellWithReuseIdentifier:PictureSelectorCellID];
    
    
}



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo{

    UIImage *scaleImage = [image scaleImageToWidth:300];
    
    NSLog(@"%@",scaleImage);
    
       // 用户选中了一张照片
    
    if (self.currentIndex <self.pictures.count) {
        
        self.pictures[self.currentIndex]=scaleImage;
       
    }else{
        [self.pictures addObject:scaleImage];
    }
    [self.collectionView reloadData];
    
    [self dismissViewControllerAnimated:YES completion:nil];

}

#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of items
    return  self.pictures.count +(self.pictures.count==HMMaxPictureCount?0:1);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
   
    
    PictureSelectorCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:PictureSelectorCellID forIndexPath:indexPath];
    
    cell.pictureDelegate=self;
    
    cell.image = indexPath.item < self.pictures.count ?self.pictures[indexPath.item]:nil;

//    cell.backgroundColor =[UIColor redColor];
    return cell;
}


/// 选择照片
/// Camera              相机
/// PhotoLibrary        照片库 － 包含相册，包括通过 iTunes / iPhoto 同步的照片，同步的照片不允许在手机删除
/// SavedPhotosAlbum    相册 － 相机拍摄，应用程序保存的图片，可以删除
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:
(NSIndexPath *)indexPath{

    if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary  ]) {
        NSLog(@"无法方位相册");
        
        return;
    }
    
    self.currentIndex =indexPath.item;
     // 访问相册
    
    UIImagePickerController *vc =[[UIImagePickerController alloc] init];
    
     vc.delegate = self;
    
    
   
    [self presentViewController:vc animated:YES completion:nil];
    
}


-(void)pictureSelectorCellClickRemoveButton:(PictureSelectorCell *)cell{

    NSLog(@"删除%@cell",cell);
  
    

    NSIndexPath *indexPath =[self.collectionView indexPathForCell:cell];
    
    if ( indexPath.item< self.pictures.count) {
        [self.pictures removeObjectAtIndex:indexPath.item];
    }
    
    [self.collectionView reloadData];
    
}

@end



@interface PictureSelectorCell ()

@property(nonatomic,strong) UIButton *pictureButton;

@property(nonatomic,strong) UIButton *removeButton;


@end

@implementation PictureSelectorCell




- (void)setImage:(UIImage *)image{
    _image =image;
    if (_image!=nil) {
        
        [self.pictureButton setImage:image forState:(UIControlStateNormal)];
        
    
        
    }else{
    
        // 显示默认的加号图片
        
        [self.pictureButton setImage:[UIImage imageNamed:@"compose_pic_add"] forState:(UIControlStateNormal)];
    }
    
    self.removeButton.hidden =(image==nil);

}


-(void)clickRemove{

    [self.pictureDelegate pictureSelectorCellClickRemoveButton:self];
    
    
}
-(instancetype)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
       
        [self setupUI];
    }
    
    return self;

}
-(void)setupUI{
    
    [self.contentView addSubview:self.pictureButton];
    [self.contentView addSubview:self.removeButton];
    
    self.removeButton.translatesAutoresizingMaskIntoConstraints=NO;
    
      self.pictureButton.frame = self.bounds;
    
    NSDictionary *dict =@{@"btn":self.removeButton};
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[btn]-0-|" options:0 metrics:nil views:dict]];
    
    [self.contentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[btn]" options:0 metrics:nil views:dict]];
    
    
    [self.removeButton addTarget:self action:@selector(clickRemove) forControlEvents:(UIControlEventTouchUpInside)];
    self.pictureButton.userInteractionEnabled= NO;
    

  self.pictureButton.imageView.contentMode =UIViewContentModeScaleAspectFill;
}


-(UIButton *)pictureButton{
    if (_pictureButton==nil) {
        
        _pictureButton=[[UIButton alloc] initWithImageName:@"compose_pic_add"];
    }
    return _pictureButton;

}

-(UIButton *)removeButton{
    if (_removeButton==nil) {
        _removeButton=[[UIButton alloc] initWithImageName:@"compose_photo_close"];
    }
    return _removeButton;
}
@end


